package com.foreverwin.jzymes.archive.controller;

import com.foreverwin.jzymes.archive.domain.DataArchive;
import com.foreverwin.jzymes.archive.service.IDataArchiveAdviceService;
import com.foreverwin.jzymes.archive.service.IDataArchiveService;
import com.foreverwin.jzymes.framework.base.AjaxResult;
import com.foreverwin.jzymes.framework.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/dataArchive")
public class DataArchiveController {

    @Autowired
    IDataArchiveService dataArchiveService;
    @Autowired
    IDataArchiveAdviceService dataArchiveAdviceService;

    @RequestMapping("/findDataArchive")
    public AjaxResult findDataArchive(){

        List<DataArchive> dataArchiveList = new ArrayList<>();
        List<DataArchive> tempDataArchiveList = new ArrayList<>();

        List<DataArchive> dataArchives = dataArchiveAdviceService.findReferDataArchiveList( null );
        for( DataArchive dataArchive : dataArchives ){
            List<DataArchive> referDataArchives = dataArchiveAdviceService.findReferDataArchiveList( dataArchive.getTableName() );
            if( referDataArchives.size() > 0 ){
                dataArchiveList.add( dataArchive );
                findReferDataArchiveList( dataArchive.getTableName(), dataArchiveList );
            }else{
                tempDataArchiveList.add( dataArchive );
            }
        }
        dataArchiveList.addAll( tempDataArchiveList );

        return AjaxResult.returnSuccess().put( "value", dataArchiveList );
    }

    public void findReferDataArchiveList( String table, List<DataArchive> dataArchiveList ){
        List<DataArchive> dataArchives = dataArchiveAdviceService.findReferDataArchiveList( table );
        for( DataArchive dataArchive : dataArchives ) {
            dataArchiveList.add( dataArchive );
            findReferDataArchiveList( dataArchive.getTableName(), dataArchiveList );
        }
    }

    @RequestMapping("/saveDataArchive")
    public AjaxResult saveDataArchive( @RequestBody List<DataArchive> dataArchiveList ){
        try{
            dataArchiveAdviceService.saveDataArchive( dataArchiveList );
            return AjaxResult.returnSuccess();
        }catch ( BusinessException e ){
            return AjaxResult.returnError( e.getMessage() );
        }
    }

}
